package com.doctor.windflower_doctor.service;

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.doctor.windflower_doctor.R;
import com.doctor.windflower_doctor.SystemApplication;
import com.doctor.windflower_doctor.actionBeen.DialogueAction;
import com.doctor.windflower_doctor.activity.DialogActivity;
import com.doctor.windflower_doctor.activity.Login;
import com.doctor.windflower_doctor.activity.QuestionOnLineActivity;
import com.doctor.windflower_doctor.db.SharedPreferencesDB;
import com.doctor.windflower_doctor.entity.DialogueBeen;
import com.doctor.windflower_doctor.util.ActivityStack;
import com.doctor.windflower_doctor.util.Constent;
import com.doctor.windflower_doctor.util.LogUtils;
import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.engineio.client.Transport;
import com.github.nkzawa.socketio.client.Ack;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Manager;
import com.github.nkzawa.socketio.client.Socket;
import com.github.nkzawa.socketio.parser.Parser;

/**
 * <p>
 * 功能 对话service
 * </p>
 * 
 * <p>
 * Copyright 北京亚普拓信息咨询服务有限公司 2014 All right reserved.
 * </p>
 * 
 * @author 皮勉 时间 2014年11月12日 下午1:39:22
 * @version 1.0 </br> 最后修改人 无
 * 
 */
public class DialogueService extends Service {
	public BroadcastReceiver serviceReceiver;
	public static final String ACTION = "com.doctor.windflower_doctor.service.DialogueService";
	public static final String ACTION_INIT = "com.doctor.windflower_doctor.service.DialogueService.init";
	public static final String ACTION_CLOSE = "com.doctor.windflower_doctor.service.DialogueService.close";
	public static final String ACTION_AUDIO = "com.doctor.windflower_doctor.service.DialogueService_audio";
	private Socket socket;
	private String currentEvent;
	private String questionId;
	private Dialog dialogLogin;
	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			LogUtils.e("================handler================");
			if (!SystemApplication.getInstance().isApplicationBroughtToBackground(DialogueService.this)) {
				Intent intent = new Intent(DialogueService.this, DialogActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@SuppressWarnings("deprecation")
	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);

	}

	@Override
	public void onCreate() {
		IOStart();
		serviceReceiver = new ServiceReceiver();
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction(ACTION);
		myIntentFilter.addAction(ACTION_INIT);
		myIntentFilter.addAction(ACTION_CLOSE);
		myIntentFilter.addAction(ACTION_AUDIO);
		registerReceiver(serviceReceiver, myIntentFilter);
		super.onCreate();
	}

	class ServiceReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			DialogueBeen dialogueBeen = new DialogueBeen();
			dialogueBeen = (DialogueBeen) intent.getExtras().getSerializable("DialogueBeen");
			String str = JSON.toJSONString(dialogueBeen);
			LogUtils.e("重置ServiceReceiver-----------------？" + str);
			if (intent.getAction().equals(ACTION)) {
				String iso = null;
				try {
					iso = Base64.encodeToString(new String(str.getBytes("UTF-8"), "ISO-8859-1").getBytes("ISO-8859-1"), Base64.NO_WRAP);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();

				}
				currentEvent = Constent.DIALOG_DOCTOR_POST_MESSAGE;
				socketSend(currentEvent, iso);
			} else if (intent.getAction().equals(ACTION_INIT)) {
				try {
					currentEvent = Constent.DIALOG_DOCTOR_INIT;
					socketSend(currentEvent, Base64.encodeToString(new String(str.getBytes("UTF-8"), "ISO-8859-1").getBytes("ISO-8859-1"), Base64.NO_WRAP));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			} else if (intent.getAction().equals(ACTION_CLOSE)) {
				try {
					currentEvent = Constent.DIALOG_DOCTOR_CLOSE_QUESTION;
					socketSend(currentEvent, Base64.encodeToString(new String(str.getBytes("UTF-8"), "ISO-8859-1").getBytes("ISO-8859-1"), Base64.NO_WRAP));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		}
	}

	void IOStart() {

		try {
			if (null != socket && socket.connected()) {
				socket.disconnect();
			}

			socket = IO.socket(Constent.URL_SOKET);
			socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {

				@Override
				public void call(Object... args) {
					Log.e("DialogueService==========1===>", "EVENT_CONNECT");
				}
			}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					Log.e("DialogueService=========2====>", "EVENT_DISCONNECT");
					// disconnect
				}
			}).on(Constent.DIALOG_DOCTOR_NEW_MESSAGE, new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					Log.e("DialogueService=========追问====>", "DIALOG_DOCTOR_NEW_MESSAGE");
					currentEvent = Constent.DIALOG_DOCTOR_NEW_MESSAGE;
					postReceiver(args);
				}
			}).on(Constent.DIALOG_DOCTOR_EVALUATE, new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					Log.e("DialogueService=========用户评价====>", "DIALOG_DOCTOR_EVALUATE");
					currentEvent = Constent.DIALOG_DOCTOR_EVALUATE;
					postReceiver(args);
				}

			}).on(Constent.SYSTEM_DOCTOR_LOGOUT, new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					Log.e("DialogueService=========被踢====>", "SYSTEM_DOCTOR_LOGOUT");
					SharedPreferencesDB.getInstance(DialogueService.this).setIsLogin(false);
					handler.sendEmptyMessage(0);
				}
			});

			// .on(自定义事件, new Emitter.Listener() {
			// @Override
			// public void call(Object... args) {
			// // 自定义事件
			// }
			// })
			socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
				@Override
				public void call(Object... args) {
					Transport transport = (Transport) args[0];
					transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
						@Override
						public void call(Object... args) {
							@SuppressWarnings("unchecked")
							Map<String, String> headers = (Map<String, String>) args[0];
							// set header
							headers.put("doctor", SharedPreferencesDB.getInstance(DialogueService.this).getDocotorId());
							if (SharedPreferencesDB.getInstance(DialogueService.this).getIsLogin())
								headers.put("login", "true");

						}
					});
				}
			}).on(Manager.EVENT_PACKET, new Emitter.Listener() { // 登入
						@Override
						public void call(Object... args) {
							@SuppressWarnings("unchecked")
							final com.github.nkzawa.socketio.parser.Packet<JSONArray> packet = (com.github.nkzawa.socketio.parser.Packet<JSONArray>) args[0];
							if (null != packet && Parser.EVENT == packet.type) {
								List<Object> list = new ArrayList<Object>(Arrays.asList(toArray(packet.data)));
								if ("foo".equals(list.remove(0))) {

								}
							}
						}
					});

			socket.connect();
		} catch (URISyntaxException e) {
			e.printStackTrace();

		}

	}

	private Object[] toArray(JSONArray array) {
		int length = array.length();
		Object[] data = new Object[length];
		for (int i = 0; i < length; i++) {
			Object v;
			try {
				v = array.get(i);
			} catch (JSONException e) {
				v = null;
			}
			data[i] = v == JSONObject.NULL ? null : v;
		}
		return data;
	}

	void socketSend(final String event, Object... obj) {
		socket.emit(event, obj, new Ack() {

			@Override
			public void call(Object... arg0) {
				Log.e("DialogueService==========3===>", arg0[0].toString());
				postReceiver(arg0);
			}

		});
	}

	void postReceiver(Object... arg0) {
		try {
			byte[] result = Base64.decode(arg0[0].toString().getBytes(), Base64.DEFAULT);
			String res = new String(result);
			Log.e("DialogueService==========4===>", res);
			DialogueAction dialogueAction = JSON.parseObject(res, DialogueAction.class);
			if (dialogueAction.success) {
				Intent intent = new Intent(QuestionOnLineActivity.ACTION);
				Bundle bundle = new Bundle();
				if (currentEvent.equals(Constent.DIALOG_DOCTOR_INIT)) {
					bundle.putBoolean("INIT", true);
					bundle.putSerializable("DialogueBeen", dialogueAction.data);
				} else if (currentEvent.equals(Constent.DIALOG_DOCTOR_POST_MESSAGE)) {
					bundle.putSerializable("DialogueBeen", dialogueAction.data);
				} else if (currentEvent.equals(Constent.DIALOG_DOCTOR_NEW_MESSAGE)) {
					bundle.putSerializable("DialogueBeen", dialogueAction.data);
				} else if (currentEvent.equals(Constent.DIALOG_DOCTOR_EVALUATE)) {
					intent = new Intent(QuestionOnLineActivity.DIALOG_DOCTOR_EVALUATE);
					bundle.putSerializable("DialogueBeen", dialogueAction.data);
				} else if (currentEvent.equals(Constent.DIALOG_DOCTOR_CLOSE_QUESTION)) {
					bundle.putSerializable("DialogueBeen", dialogueAction.data);
				}
				intent.putExtras(bundle);
				DialogueService.this.sendBroadcast(intent);
			} else {
				Log.e("DialogueService==========6===>", dialogueAction.message);
				Toast.makeText(DialogueService.this, dialogueAction.message, Toast.LENGTH_SHORT).show();

			}
		} catch (Exception e) {

			// TODO Auto-generated catch block
			e.printStackTrace();

		}
	}

	@Override
	public void onDestroy() {
		if (serviceReceiver != null)
			unregisterReceiver(serviceReceiver);
		if (socket != null)
			socket.disconnect();
		super.onDestroy();

	}

}